package com.example.listdetail;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

class HttpUtil {
    /**
     * JSON 解析方法
     * @param jsonData
     * @return
     */
    static String JSONString(String jsonData){
        try {
            StringBuffer sb = new StringBuffer();
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                sb.append(jsonObject.getString("name")+"\n");
                sb.append(jsonObject.getString("content")+"\n");
            }
            return sb.toString();
        } catch (JSONException e) {
            Log.e("JSONException错误", "readContent: "+e.toString());
            return e.toString();
        }
    }
    //登录
    static void loginWithOkHttp(String address,String account,String password,okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("loginAccount",account)
                .add("loginPassword",password)
                .build();
        Request request = new Request.Builder()
                .url(address)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }
    //注册
    static void registerWithOkHttp(String address,String account,String password,okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("registerAccount",account)
                .add("registerPassword",password)
                .build();
        Request request = new Request.Builder()
                .url(address)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }
    //获取一个数据
    static void getWithOkHttp(okhttp3.Callback callback){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://cnodejs.org/api/v1/topics?tab=share")
                .build();
        client.newCall(request).enqueue(callback);
    }

    //获取一个详情
    static void getDetail(okhttp3.Callback callback,String id){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://cnodejs.org/api/v1/topic/"+id)
                .build();
        client.newCall(request).enqueue(callback);
    }
}